package com.example.gui;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import org.json.JSONException;
import org.json.JSONObject;

public class SetPostActivity extends AppCompatActivity {

    private EditText editTextTitle;
    private EditText editTextContent;
    private Button buttonPublish;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_set_post);

        editTextTitle = findViewById(R.id.editTextTitle);
        editTextContent = findViewById(R.id.editTextContent);
        buttonPublish = findViewById(R.id.buttonPublish);

        buttonPublish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 获取用户输入的标题和内容
                String title = editTextTitle.getText().toString();
                String content = editTextContent.getText().toString();

                // 保存帖子到 SharedPreferences
                savePost(title, content);

                // 返回主页并加载所有帖子
                Intent intent = new Intent(SetPostActivity.this, HomeActivity.class);
                startActivity(intent);

                finish();
            }
        });

    }

    private void savePost(String title, String content) {
        SharedPreferences sharedPreferences = getSharedPreferences("UserData", MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();

        // 将帖子的标题和内容组成 JSON 字符串保存到 SharedPreferences
        try {
            JSONObject postJson = new JSONObject();
            postJson.put("title", title);
            postJson.put("content", content);

            editor.putString(title, postJson.toString());
            editor.apply();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
